package com.yunkont.pigcontrol.fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yunkont.pigcontrol.R;
import com.yunkont.pigcontrol.activity.AllPigActivity;
import com.yunkont.pigcontrol.adapter.HistroyAllAdapter;
import com.yunkont.pigcontrol.adapter.HistroyDetailAdapter;
import com.yunkont.pigcontrol.bean.HistoryBean;
import com.yunkont.pigcontrol.net.UrlValue;
import com.yunkont.pigcontrol.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by ZJB on 2017/9/21.
 *
 * @ copyright: iwhere chengdu technology
 */

public class SeconedFragment extends Fragment {

    @Bind(R.id.ed_startTime)
    TextView tvStartTime;
    @Bind(R.id.ed_endTime)
    TextView tvEndTime;
    @Bind(R.id.tv_pigId)
    TextView tvPigId;
    @Bind(R.id.rb1)
    RadioButton rb1;
    @Bind(R.id.rb2)
    RadioButton rb2;
    @Bind(R.id.ryclerview)
    RecyclerView ryclerview;
    @Bind(R.id.ryclerview2)
    RecyclerView ryclerview2;
    @Bind(R.id.rg_tab)
    RadioGroup rgTab;
    private boolean isStart = true;
    private HistoryBean historyBean = new HistoryBean();
    private HistroyAllAdapter adapter1;
    private HistroyDetailAdapter adapter2;
    private int page = 0;
    private boolean isLoading = false;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_second, container, false);
        ButterKnife.bind(this, inflate);
        initView();
        return inflate;
    }


    private void initView() {
        historyBean.setData(new HistoryBean.DataBeanX());
        initDatePicker();
        tvPigId.setHint("猪编号：");
        rgTab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb1) {
                    ryclerview2.setVisibility(View.GONE);
                    ryclerview.setVisibility(View.VISIBLE);
                } else {
                    ryclerview.setVisibility(View.GONE);
                    ryclerview2.setVisibility(View.VISIBLE);
                }
            }
        });

        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        ryclerview.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        ryclerview2.setLayoutManager(linearLayoutManager);

        adapter1 = new HistroyAllAdapter(getActivity(),historyBean);
        adapter2 = new HistroyDetailAdapter(getActivity(),historyBean);

        ryclerview.setAdapter(adapter1);
        ryclerview2.setAdapter(adapter2);

        ryclerview2.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int itemCount = adapter2.getItemCount();
                int lastCompletelyVisibleItemPosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition == itemCount -1){
                    if(isLoading)return;
                    page++;
                    goSearch();
                }
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.ed_startTime, R.id.ed_endTime, R.id.tv_pigId, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ed_startTime:
                isStart = true;
                datePickerDialog.show();
                break;
            case R.id.ed_endTime:
                isStart = false;
                datePickerDialog.show();
                break;
            case R.id.tv_pigId:
                startActivityForResult(new Intent(getActivity(), AllPigActivity.class), 90);
                break;
            case R.id.btn_search:
                goSearch();
                break;
        }
    }


    private DatePickerDialog datePickerDialog;

    private void initDatePicker() {
        if (datePickerDialog == null) {
            Calendar instance = Calendar.getInstance();
            datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                    i1 = i1 + 1;
                    String year = i + "-";
                    String month = i1 < 10 ? ("0" + (i1)) : (i1) + "";
                    String day = i2 < 10 ? ("0" + (i2)) : (i2) + "";

                    if (isStart) {
                        tvStartTime.setText(year + month + "-" + day);
                    } else {
                        tvEndTime.setText(year + month + "-" + day);
                    }
                }
            }, instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), instance.get(Calendar.DAY_OF_MONTH));
        }
    }

    private String lastPid = "";
    private void goSearch() {
        String endTime = tvEndTime.getText().toString();
        String startTime = tvStartTime.getText().toString();
        String pigId = tvPigId.getText().toString();
        if (TextUtils.isEmpty(endTime) || TextUtils.isEmpty(startTime)) {
            Toast.makeText(getActivity(), "请输入查询时间", Toast.LENGTH_SHORT).show();
            return;
        }

        int i = Utils.daysBetween(startTime, endTime);
        if (i > 5 || i < 0) {
            Toast.makeText(getActivity(), "查询时间不超过5天,\n结束时间不得大于开始时间", Toast.LENGTH_LONG).show();
            return;
        }

        if (TextUtils.isEmpty(pigId)) {
            Toast.makeText(getActivity(), "请输入猪编号", Toast.LENGTH_SHORT).show();
            return;
        }

        String end = Utils.date2TimeStamp(endTime, "yyyy-MM-dd");
        String start = Utils.date2TimeStamp(startTime, "yyyy-MM-dd");

        isLoading = true;
        if(!lastPid.equals(pigId)){
            page = 0;
            adapter2.clearData();
        }else {
            page++;
        }
        lastPid = pigId;
        OkHttpUtils.get()
                .url(UrlValue.history)
                .addParams("t1", start)
                .addParams("t2", end)
                .addParams("pid", pigId)
                .addParams("pageSize", "20")
                .addParams("page",page+"")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getActivity(), "网络错误：" + e.toString(), Toast.LENGTH_SHORT).show();
                        isLoading = false;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("UrlValue.history", "onResponse: "+response );

                        try {
                            Log.e("UrlValue.history1", "onResponse: "+response );
                            HistoryBean historyBean = JSON.parseObject(response, HistoryBean.class);
                            Log.e("UrlValue.history2", "onResponse: "+historyBean.getCount().size()+" "+historyBean.getData().getData().size() );

                            adapter1.setHistoryBean(historyBean);
                            adapter2.setHistoryBean(historyBean);
                            isLoading = false;

                            if(page+1 == historyBean.getData().getTotalPage()){
                               Toast.makeText(getActivity(),"没有数据了~",Toast.LENGTH_SHORT).show();
                                isLoading = true;
                            }else {
                                Toast.makeText(getActivity(),"正在加载~",Toast.LENGTH_SHORT).show();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

        String url = UrlValue.history+"t1="+start+"&t2="+end+"&pid="+pigId+"&pageSize=20&page="+page;
        Log.e("zjb", "goSearch: "+url );
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 90) {
            if (data != null) {
                String pigId = data.getStringExtra("pigId");
                if (!TextUtils.isEmpty(pigId)) {
                    tvPigId.setText(pigId);
                }
            }
        }
    }


}
